#! /usr/bin/python
# encoding=utf-8
# Created by Fenglu Niu on 2024/3/22 11:30
import functools
import time
import hashlib

from enum import Enum
from flask import request, jsonify

name = 'common'

SALT = 'ZERO_JX_DEEP_SEARCH:'
REQ_CHECK = "REQ_CHECK"

class Engine(Enum):
    Baidu = 'baidu'
    Google = 'google'

def req_check(func):
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        if REQ_CHECK == "REQ_CHECK":
            result = {}
            timestamp = request.headers.get('timestamp')
            sign = request.headers.get('sign')
            if not timestamp:
                result.setdefault('code', 400)
                result.setdefault('msg', "header必须传timestamp,单位秒")
                return jsonify(result)
            if not sign:
                result.setdefault('code', 400)
                result.setdefault('msg', "header必须传sign")
                return jsonify(result)
            if abs(int(time.time()) - int(timestamp)) > 60:
                result.setdefault('code', 400)
                result.setdefault('msg', "时间戳误差大于60秒，请校正机器时间")
                return jsonify(result)
            server_sign = hashlib.md5((SALT + str(timestamp)).encode(encoding='utf-8')).hexdigest()
            if sign != server_sign:
                result.setdefault('code', 400)
                result.setdefault('msg', "签名验证失败，禁止访问")
                return jsonify(result)
        return func(*args, **kwargs)

    return decorator


# 日志模块
import logging.config
import logging
from logging.handlers import TimedRotatingFileHandler
import os

# 创建日志目录
logs_folder = 'logs'
if not os.path.exists(logs_folder):
    os.mkdir(logs_folder)

# 日志配置字典
logging_config = {
    'version': 1,
    'formatters': {
        'standard': {
            'format': '%(asctime)s - %(levelname)s [%(name)s/%(filename)s:%(lineno)d] - %(message)s'
        }
    },
    'handlers': {
        'root': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'formatter': 'standard',
            'filename': f'{logs_folder}/app.log',
            'when': 'midnight',
            'interval': 1,  # Rotate daily
            'backupCount': 7,  # Keep 7 days of logs
            'encoding': 'UTF-8',
        },
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'standard',
            'stream': 'ext://sys.stdout'
        }
    },
    'root': {
        'handlers': ['root', 'console'],
        'level': 'INFO',
    },
}
# 创建日志配置字典
logging.config.dictConfig(logging_config)
logging.getLogger("werkzeug").disabled = True

import inspect


def get_logger():
    module_name = ''
    # Get the caller's frame
    caller_frame = inspect.stack()[1]
    # Extract the module name from the frame
    caller_module = inspect.getmodule(caller_frame[0])
    if caller_module:
        module_name = caller_module.__name__
    else:
        module_name = '__main__'

    l = logging.getLogger(module_name)
    return l
